﻿using System;
using System.Collections.Generic;
using System.Web;
using log4net;

namespace SharePoint.Orm {
	public class UniversalContextStack<T> : ContextStackSkeleton<T> where T : class {
		private static readonly ILog _log = LogManager.GetLogger(typeof(UniversalContextStack<T>));
		private static readonly object _myLock = new object();

		[ThreadStatic]
		private readonly Stack<T> _threadStackStack = new Stack<T>();

		protected override void DoStackOperation(Action<Stack<T>> action) {
			lock (_myLock) {
				HttpContext httpContext = HttpContext.Current;
				if (httpContext != null) {
					WebContextStack<T>.DoStackOperation(httpContext, action);
				} else {
					action(_threadStackStack);
					_log.Debug("Context stack has " + _threadStackStack.Count + " items.");
				}
			}
		}
	}
}
